#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqLsit.h"

void SeqListInit(SeqList* ps)
{
	assert(ps);
	ps->arr = (SLDateType*)malloc(sizeof(SLDateType) * INIT_CAPACITY);
	if (ps->arr == NULL)
	{
		perror("malloc fail!");
		return;
	}
	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}


void SeqListDestroy(SeqList* ps)
{
	
	assert(ps);
	free(ps->arr);

	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", *(ps->arr + i));
	}
	printf("\n");
}

void CheckCAPACITY(SeqList* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLDateType* tmp = (SLDateType*)realloc(ps->arr, 2 * sizeof(SLDateType) * ps->capacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = 2 * ps->capacity;
	}
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	/*assert(ps);
	if (ps->size == ps->capacity)
	{
		SLDateType* tmp = (SLDateType*)realloc(ps->arr, 2 * sizeof(SLDateType) * ps->capacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = 2 * ps->capacity;
	}*/
	CheckCAPACITY(ps);
	ps->arr[ps->size++] = x;

	//SeqListInsert(ps, ps->size, x);
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps);
	assert(ps->size);
	ps->size--;
}


void SeqListPushFront(SeqList* ps, SLDateType x)
{
	assert(ps);
	/*if (ps->size == ps->capacity)
	{
		SLDateType* tmp = (SLDateType*)realloc(ps->arr, 2 * sizeof(SLDateType) * ps->capacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = 2 * ps->capacity;
	}*/
	CheckCAPACITY(ps);
	for(int i = ps->size; i > 0; i--)
	{
		*(ps->arr + i) = *(ps->arr + i - 1);
	}
	ps->arr[0] = x;
	ps->size++;
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i+1];
	}
	ps->size--;
}

void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	CheckCAPACITY(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps && ps->size);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i < ps->size; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}